package net.ewon.avatar.agent.impl;

import java.io.File;
import java.io.IOException;
import java.util.List;

import net.ewon.avatar.agent.AvatarPackageRepo;
import net.ewon.avatar.agent.exception.OperationFailureException;
import net.ewon.avatar.common.pkg.AvatarPackageFile;
import net.ewon.avatar.common.pkg.Version;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

public abstract class AvatarPackageAbstractRepo implements AvatarPackageRepo {

	private static final Logger logger = Logger
			.getLogger(AvatarPackageAbstractRepo.class);

	protected String baseLocation;

	public AvatarPackageAbstractRepo(String baseLocation) {
		this.baseLocation = baseLocation;
		normalize();
		logger.info("The base location is: " + this.baseLocation);
	}

	public String getNormalizedBaseLocation() {
		return this.baseLocation;
	}

	public boolean exists(String name, Version version) {
		return new File(getPackageLocation(name, version)).exists();
	}

	public void install(List<AvatarPackageFile> avatarPackageFiles)
			throws OperationFailureException {
		for (AvatarPackageFile avatarPackageFile : avatarPackageFiles) {
			String file = getAbsolutePackageFilePath(avatarPackageFile
					.getName());
			try {
				FileUtils.writeByteArrayToFile(new File(file),
						avatarPackageFile.getData());
			} catch (IOException e) {
				deleteDirs(this.baseLocation + File.separator
						+ avatarPackageFile.getName().split("/")[0]);
				throw new OperationFailureException("The package file: " + file
						+ " can't be created.", e);
			}
		}
	}

	private void deleteDirs(String dir) {
		try {
			FileUtils.deleteDirectory(new File(dir));
		} catch (IOException e) {
			logger.error("The dir: " + dir + " can't be deleted.", e);
		}
	}

	public abstract String getAbsolutePackageFilePath(String fileName);

	protected abstract void normalize();

	private String getPackageLocation(String name, Version version) {
		return baseLocation + File.separator + name + File.separator + version;
	}

}
